package top.chenyaohua.init.imp;


import com.google.auto.service.AutoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.chenyaohua.init.abstractInit.AbstractInitExecution;
import top.chenyaohua.utils.FileUtils;
import top.chenyaohua.utils.PropertieUtils;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@AutoService(AbstractInitExecution.class)
public class ScanInit extends AbstractInitExecution {


    protected final static Logger LOGGER = LoggerFactory.getLogger(ScanInit.class);


    private ArrayList<String> list;


    public ScanInit () {
        super(1);
    }



    @Override
    public boolean init () {
       // new Thread(ScanInit.this::scan,"扫描包路径线程").start();
        return this.scan();
    }

    protected  boolean scan(){
        LOGGER.debug("开始扫描class文件");

        this.list = Optional.ofNullable(list).orElseGet(ArrayList::new);

        String scanPack = PropertieUtils.getProperties("app.properties").getProperty("scan.package");
        URL url = Thread.currentThread().getContextClassLoader().getResource("");

        String[] pacs = scanPack.split(",");

        try {

            for (int i = 0; i < pacs.length; i++) {
                URI uri = url.toURI();
                List<String> classNames = FileUtils.getClassNames(uri, pacs[i]);
                this.list.addAll( classNames );
            }
            LOGGER.debug("扫描到的包信息 classNames={}",list);
            return true;
        }catch (URISyntaxException e){
            LOGGER.error("扫描包下的类路径失败:",e);
            return false;
        }

    }

    protected  ArrayList<String>  getPackages(){

        return this.list;
    }

}
